package servlet;

import entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JdbcUtil;
import util.JsonUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/show")
public class ShowServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ShowServlet.service()");

//        response.setContentType("text/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter out=response.getWriter();

        Integer id=Integer.parseInt(request.getParameter("id"));

        User user=null;

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_user ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setInt(1,id);

            rs=ps.executeQuery();

            if(rs.next()){
                user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
            }

            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(rs,ps,con);
        }

//        String json="{\"id\":"+user.getId()+",\"username\":\""+user.getUsername()+"\",\"password\":\""+user.getPassword()+"\",\"phone\":\""+user.getPhone()+"\",\"address\":\""+user.getAddress()+"\"}";

        String json=JsonUtil.toJson(user);

        out.println(json);
    }
}















